<template>
	<div class="section" v-loading="loading.status" :element-loading-text="loading.txt">
		<div class="pointMark_video">
			<template v-if="1">
				<div id="newSliceDom">
					<!-- <video
                        id="sliceVideoPlayer"
                        ref="sliceVideoPlayer"
                        class="video-js vjs-big-play-centered"
                        width="100%"
                        height="100%"
                        oncontextmenu="return false;"
                        disablePictureInPicture
                        controlslist="nodownload">
                    </video> -->
					<dplayer key="dplayer" ref="dplayer" :playParam.sync="playerOptions">
					</dplayer>
				</div>
			</template>
			<img v-else src="../../../../static/images/image08.png">
		</div>
		<div class="publishFrom">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
				<div class="publishFrom_if clear">
					<el-form-item label="开始时间" prop="start_time" class="publishFrom_if_l fl">
						<span>
							<el-time-picker v-model="ruleForm.start_time" value-format="HH:mm:ss" :clearable="false" :editable="false"
								:picker-options="{
									format: 'HH:mm:ss',
									selectableRange: timeMaxStart
								}" placeholder="任意时间点">
							</el-time-picker>
						</span>
						<i class="el-icon-location" @click="getVideoPlaySTime"></i>
					</el-form-item>
					<!--  -->
					<el-form-item label="结束时间" prop="end_time" class="publishFrom_if_l fr">
						<span>
							<el-time-picker v-model="ruleForm.end_time" value-format="HH:mm:ss" :clearable="false" :editable="false"
								:picker-options="{
									format: 'HH:mm:ss',
									selectableRange: timeMaxEnd
								}" placeholder="任意时间点">
							</el-time-picker>
						</span>
						<i class="el-icon-location" @click="getVideoPlayETime"></i>
					</el-form-item>
				</div>
				<el-form-item label="视频切片" prop="name">
					<el-input v-model.trim="ruleForm.name" placeholder="视频切片，最多可输入20个字"></el-input>
				</el-form-item>
				<el-form-item label="视频备注" prop="comment">
					<el-input v-model.trim="ruleForm.comment" placeholder="切片备注，最多可输入20个字"></el-input>
				</el-form-item>
				<el-form-item class="buttonCSS publishFrom_btn" label-width="0">
					<!-- <el-checkbox v-model="ruleForm.is_virtual">虚拟切片</el-checkbox> -->
					<!-- <el-checkbox v-model="ruleForm.is_micro">推送微课</el-checkbox> -->
					<!-- <el-button @click="resetForm('ruleForm')" type="primary" plain>取消</el-button> -->
					<span class="slice-tips" @click="infoVisibe = true"><i class="el-icon-info"></i></span>
					<el-button type="primary" @click="submitForm('ruleForm')">生成切片</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="publishFrom_table">
			<template>
				<el-table border :data="listData" style="width: 100%">
					<el-table-column prop="cut_name" label="切片名称" width="300">
					</el-table-column>
					<el-table-column prop="video_start_time" label="开始时间" width="80">
					</el-table-column>
					<el-table-column prop="video_end_time" label="结束时间" width="80">
					</el-table-column>
					<!-- <el-table-column
						prop=""
						label="切片类型"
						width="70">
						<template slot-scope="scope">
							{{ parseInt(scope.row.is_virtual) === 1 ? '虚拟切片' : '物理切片'}}
						</template>
					</el-table-column> -->
					<!-- <el-table-column
						prop=""
						label="是否微课"
						width="70">
						<template slot-scope="scope">
							{{ parseInt(scope.row.is_micro) === 1 ? '是' : '否'}}
						</template>
					</el-table-column> -->
					<el-table-column prop="comment" label="备注" align="center" show-overflow-tooltip width="169">
					</el-table-column>
					<el-table-column prop="" label="状态" align="center" show-overflow-tooltip width="169">
						<template slot-scope="scope">
							<span :class="scope.row.status == '切片失败' ? 'delete-button' : ''">{{ scope.row.status }}</span>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center">
						<template slot-scope="scope">
							<el-button v-if="scope.row.status == '正常切片'" @click="videoView(scope.row)" type="text">预览</el-button>
							<el-button @click="deleteCut(scope.row)" type="text" class="delete-button" size="small">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</template>
			<!--  -->
			<div class="pageBox" v-show="total_number > 10">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page="listParam.page_index" :page-size="listParam.page_size"
					layout="total,  prev, pager, next, jumper" :total="total_number">
				</el-pagination>
			</div>
		</div>

		<transition name="el-fade-in-linear">
			<div class="masking" :class="{ activeLive: isActive }">
				<div class="maskingBox">
					<div class="masking_h">
						<span>切片预览</span>
						<i class="el-icon-close" @click="viewClose"></i>
					</div>
					<div class="masking_c">
						<!-- <nativeVideo v-if="showVideoPlayer" :playParam.sync="playParam">
						</nativeVideo> -->
						<dplayerV v-if="showVideoPlayer" :playParam.sync="playParam">
						</dplayerV>
					</div>
				</div>
			</div>
		</transition>

		<el-dialog title="提示" :visible.sync="infoVisibe" :close-on-click-modal="false" :close-on-press-escape="false"
			width="400px">
			切片大小请控制在4G以内，切片视频过大将影响切片等待时间和系统运行内存
			<div slot="footer" class="dialog-footer"></div>
		</el-dialog>
	</div>
</template>
<script>
import nativeVideo from '../../../public/nativeVideo';
import dplayer from '@/components/public/dplayer.vue';
import dplayerV from '@/components/public/dplayerV.vue';
export default {
	props: ['compParam', 'activeIndex'],
	name: '',
	components: {
		dplayer,
		dplayerV,
		// nativeVideo,
	},
	data() {
		return {
			player: null, // 播放器
			infoVisibe: false, // 提示信息
			thisIndex: '4',
			total_number: 0,
			loading: {
				status: false,
				txt: '获取数据...'
			},
			timeMaxStart: '00:00:00 - 00:00:00',
			timeMaxEnd: '00:00:00 - 00:00:00',
			currentPage4: 4,
			ruleForm: {
				slice: '', //开始时间
				remarks: '', //视频备注
				end_time: '00:00:00', //结束时间
				start_time: '00:00:00', //开始时间
				is_virtual: false, //虚拟切片
				is_micro: false, //推送微课

			},
			listData: [],
			listParam: {
				video_id: 0,
				page_index: 1,
				page_size: 10,
			},
			rules: {
				name: [
					{ validator: this.checkValue, trigger: 'blur' },
					{ required: true, message: '请输入视频切片名称', trigger: 'blur' },
					{ min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
				],
				comment: [
					{ required: false, message: '请输入视频备注', trigger: 'blur' },
					{ min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
				],
				start_time: [
					{ required: true, message: '请输入开始时间', trigger: 'blur' },
				],
				end_time: [
					{ required: true, message: '请输入结束时间', trigger: 'blur' },
				]
			},
			// playerOptions : {
			//     loop: false,
			//     height: '360',
			//     sources: [{
			//         type: "rtmp/mp4",
			//         src: "blabla"
			//     }],
			//     techOrder: ['flash'],
			//     autoplay: false,
			//     controls: true,
			//     poster: "",
			// 	controlBar: {
			//       	timeDivider: true,
			//      	durationDisplay: true,
			//      	remainingTimeDisplay: false,
			//       	fullscreenToggle: true  //全屏按钮
			//     }
			// },
			// playerOptions: {
			// 	loop: false, // true -- 视频一结束就重新开始
			// 	controls: true,
			// 	fluid: false,
			// 	autoplay: false, // true--浏览器准备好时开始回放
			// 	height: '360',
			// 	poster: "", // 封面地址
			// 	language: 'zh-CN',
			// 	// techOrder: ['flash'],
			// 	sources: [{
			// 		type: "application/x-mpegURL",
			// 		src: this.compParam.play_url // 视频播放路径
			// 	}],
			// 	controlBar: {
			// 		children: [
			// 			{ name: 'playToggle' }, // 播放按钮
			// 			{ name: 'currentTimeDisplay' }, // 当前已播放时间
			// 			{ name: 'progressControl' }, // 播放进度条
			// 			{ name: 'durationDisplay' }, // 总时间
			// 			{
			// 				name: 'volumePanel', // 音量控制
			// 				inline: false, // 不使用水平方式
			// 			},
			// 			{ name: 'FullscreenToggle' } // 全屏
			// 		]
			// 	},
			// },
			playerOptions: {
				play_url: this.compParam.play_url,
			},

			tableData: [],
			isActive: true,
			showVideoPlayer: false,
			playParam: { play_url: ''},
		}
	},
	computed: {
		videoId() {
			return this.compParam.id;
		}
	},
	watch: {
		'videoId': {
			handler(n) {
				this.initFunc();
			},
			deep: true
		},
	},
	mounted() {
		console.log(this.compParam)
		// this.initPlay();
		this.initFunc();
	},
	beforeDestroy() {
		clearInterval(this.timer);
		this.player && this.player.dispose();
	},
	beforeRouteLeave(to, from, next) {
		clearInterval(this.timer);
		this.player && this.player.dispose();
		next(true);
	},
	methods: {
		/**
		 * 改变进度条
		 */
		onSlicePlay() {
			this.debounce(() => {
				var normal_currentTime = this.player.currentTime();
				var unnormal_currentTime = this.player.currentTime();
				if (normal_currentTime.toString() == unnormal_currentTime.toString()) {
					this.player.pause();
					this.player.play();
				}
			}, 100);
		},
		/**
		 * 延迟处理
		 */
		debounce(func, wait, immediate) {
			let timeout, args, context, timestamp, result;
			const later = function () {
				// 据上一次触发时间间隔
				const last = +new Date() - timestamp;

				// 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
				if (last < wait && last > 0) {
					timeout = setTimeout(later, wait - last);
				} else {
					timeout = null;
					// 如果设定为immediate===true，因为开始已经调用过了此处无需调用
					if (!immediate) {
						result = func.apply(context, args);
						if (!timeout) context = args = null;
					}
				}
			};
			return function (...args) {
				context = this;
				timestamp = +new Date();
				const callNow = immediate && !timeout;
				// 如果延时不存在，重新设定延时
				if (!timeout) timeout = setTimeout(later, wait);
				if (callNow) {
					result = func.apply(context, args);
					context = args = null;
				}

				return result;
			};
		},
		checkValue(rule, value, callback) {
			if (!checkSpace(value)) {
				callback(new Error("请输入有效值"));
			} else {
				callback();
			}
		},
		/**
		 * 播放器初始
		 */
		initPlay() {
			let self = this;
			this.player && this.player.dispose();
			let sliceVideoPlayer = document.getElementById('newSliceDom');
			sliceVideoPlayer.innerHTML = '<video id="sliceVideoPlayer" class="video-js vjs-big-play-centered" width="100%" height="100%" oncontextmenu="return false;" disablePictureInPicture controlslist="nodownload"> </video>'
			this.player = this.$videojs('sliceVideoPlayer', this.playerOptions, function onPlayerReady() { })

			// 初始音量50%
			this.player.volume(0.5)

			this.player.on('play', function () {
				self.onSlicePlay();
			})
		},
		initFunc() {
			// this.player.src({ type : "rtmp/mp4", src : this.compParam.play_url }) ;
			this.timeMaxStart = '00:00:00 - ' + this.compParam.length;
			this.timeMaxEnd = '00:00:00 - ' + this.compParam.length;
			this.getCutList();
			clearInterval(this.timer);
			this.timer = setInterval(() => {
				this.getCutList();
			}, 10000);
		},
		viewClose() {
			this.showVideoPlayer = false;
			this.isActive = true
		},
		videoView(obj) {
			this.$refs.dplayer.player.pause();
			this.playParam.play_url = obj.pc_play_cut_url;
			if (obj.is_virtual === 1) {
				this.playParam.start_time = obj.start_time;
				this.playParam.end_time = obj.end_time;
			} else {
				this.playParam.start_time = null;
				this.playParam.end_time = null;
			}
			this.showVideoPlayer = true;
			this.isActive = false
		},
		saveCut() {
			this.loading.status = true;
			this.loading.txt = '保存数据...';
			var start_time = this.ruleForm.start_time.split(":"); // 时间字符分割 
			var end_time = this.ruleForm.end_time.split(":"); // 时间字符分割 
			var start_timeSeconds = parseInt(start_time[0] * 3600) + parseInt(start_time[1] * 60) + parseInt(start_time[2]); // 时间转成秒数
			var end_timeSeconds = parseInt(end_time[0] * 3600) + parseInt(end_time[1] * 60) + parseInt(end_time[2]); // 时间转成秒数
			if (end_timeSeconds <= start_timeSeconds) {
				this.$message.error('切片结束时间小于或等于切片开始时间');
				this.loading.status = false;
				return;
			}
			var params = {
				video_id: this.compParam.id,
				name: this.ruleForm.name,
				comment: this.ruleForm.comment,
				start_time: start_timeSeconds,
				end_time: end_timeSeconds,
				is_virtual: this.ruleForm.is_virtual ? 1 : 0,
				is_micro: this.ruleForm.is_micro ? 1 : 0
			}

			let success = (data => {
				this.loading.status = false;
				this.$message.success(data.msg)
				this.initFunc();
				this.resetForm('ruleForm');
			});
			let fail = (data => {
				this.loading.status = false;
				this.$message.error(data.msg)
			})
			this.$ajax.post('api/video/video_cut', params, { func: { success: success, fail: fail } })
		},
		deleteCut(obj) {
			let yes = (data => {
				let success = (data => {
					if (this.listData.length - 1 === 0) {
						if (this.listParam.page_index > 1) {
							this.listParam.page_index--;
						} else {
							this.listParam.page_index = 1;
						}
					}

					this.getCutList();
					this.$message.success(data.msg)
				})
				this.$ajax.delete('api/video/video_cut', { params: { id: obj.cut_id }, func: { success: success } })
			})
			let cancel = (data => { })
			this.e_confirm({ yes: yes, cancel: cancel, txt: '确定将 ' + obj.cut_name + ' 删除吗？' });
		},
		//视频信息
		getCutList() {
			this.loading.status = true;
			this.loading.txt = '获取数据...';
			this.listParam.video_id = this.compParam.id;
			if (is_empty(this.compParam.id) || parseInt(this.compParam.id) === 0) {
				this.loading.status = false;
				this.total_number = 0;
				this.listData = []
				return false;
			}
			let success = (data => {
				this.loading.status = false;
				this.total_number = data.data.data_sum;
				this.listData = data.data.data
				for (var i = this.listData.length - 1; i >= 0; i--) {
					var newTime = formatSeconds(this.listData[i].video_time);
					this.listData[i].video_time = newTime.hour + ':' + newTime.minute + ':' + newTime.second
				}
			});
			let fail = (data => {
				this.loading.status = false;
				this.$message.error(data.msg)
			})
			this.$ajax.get('api/video/video_cut_list', { params: this.listParam, func: { success: success } })
		},
		getVideoPlaySTime() {
			// var nowTime = formatSeconds(this.player.currentTime());
			// this.ruleForm.start_time = nowTime.hour + ':' + nowTime.minute + ':' + nowTime.second
			let nowTime = formatSeconds(this.$refs.dplayer._data.videoCurrentTime)
			this.ruleForm.start_time = nowTime.hour + ':' + nowTime.minute + ':' + nowTime.second


		},
		getVideoPlayETime() {
			this.$refs.dplayer.player.pause();
			let nowTime = formatSeconds(this.$refs.dplayer._data.videoCurrentTime)
			this.ruleForm.end_time = nowTime.hour + ':' + nowTime.minute + ':' + nowTime.second
		},
		handleSizeChange(val) {
			this.listParam.page_index = 1;
			this.listParam.page_size = val;
			this.getCutList()
		},
		handleCurrentChange(val) {
			this.listParam.page_index = val;
			this.getCutList();
		},
		//表单验证
		submitForm(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.saveCut();
				} else {
					return false;
				}
			});
		},
		resetForm(formName) {
			this.$refs[formName].resetFields();
		},
	},
}
</script>

<style lang="scss">
.section {
	.publishFrom_table {
		width: 920px;
	}

	#newSliceDom {
		height: 400px;
	}

	.slice-tips {
		display: inline-block;
		font-size: 16px;
		color: #DAA017;
		cursor: pointer;
	}

	.publishFrom {
		margin-top: 30px;
	}

	.publishFrom_btn {
		width: 920px;
		text-align: right;

		button {
			margin-left: 30px;
		}
	}

	.el-icon-location {
		padding: 7px;
		font-size: 20px;
		color: #348efc;
		background: #E8F2FF;
		border-radius: 3px;
		vertical-align: middle;
		cursor: pointer;
	}

	.masking {
		display: block;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		transition: .5s;
		background: rgba(0, 0, 0, .3);
		z-index: 4;

		.maskingBox {
			position: absolute;
			top: 20%;
			left: 50%;
			width: 800px;
			margin-left: -400px;
			background: #fff;
		}

		.masking_h {
			padding: 10px 15px;
			background: #348EFC;
			text-align: center;
			text-align-last: justify;

			>span,
			>i {
				font-size: 16px;
				text-align-last: initial;
				display: inline-block;
				vertical-align: middle;
				color: #fff;
			}

			>i {
				cursor: pointer;
			}
		}

		.masking_c {
			padding: 15px;
		}

	}

	.activeLive {
		opacity: 0;
		visibility: hidden;
	}

}
</style>